<template>
  <div>
    <el-affix>
      <el-menu
          style="width: 100%;font-weight: bold;--el-menu-hover-bg-color: #FFFFFF"
          mode="horizontal"
          text-color="black"
          background-color="#FFFFFF"
          active-text-color="#000000"
          router
      >
        <el-menu-item index="/">
          <img
              style="width: 110px;margin-bottom: 2px;margin-left: 20px"
              src="../assets/images/flower-logo.jpg"
              alt="flower-log"
          /></el-menu-item>
        <el-menu-item index="/" style="margin-left: 30px" class="marLefr">首页</el-menu-item>
        <el-menu-item @click="buy" index="/buy" class="marLefr">鲜花分类</el-menu-item>

        <div class="header_right">
          <!--            搜索框-->
          <div class="search-container" style="display: flex; align-items: center;">
            <div v-if="isSearchIconVisible" class="icon-ht" style="margin-right: 20px;">
              <a href=" " @click.prevent="toggleSearch">
                <el-icon title="搜索" style="flex: 1;">
                  <Search/>
                </el-icon>
              </a>
            </div>
            <div v-else class="search-box" style="flex: 1;">
              <el-input
                  v-model="data.search"
                  style="width: 220px; height: 30px;margin-top: 28px;padding-right: 20px;font-size: 13px;"
                  placeholder="请输入商品名称"
                  clearable
                  @keyup.enter="handleSearch"
                  :prefix-icon="Search"
              >
                <template #append>
                  <el-button @click="load" type="warning">搜索</el-button>
                </template>
              </el-input>
            </div>
          </div>
          <!--            登录-->
          <div class="icon-dl">
            <a href="/login" v-if="!data.isLoggedIn">
              <el-icon title="登录" style="flex: 1">
                <User/>
              </el-icon>
            </a>

            <!-- 当登录后显示头像和下拉框，未登录时隐藏 -->
            <el-dropdown v-else style="display: inline-flex;">
              <el-avatar :size="35" :src="data.user.avatar"/>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="pace">个人信息</el-dropdown-item>
                  <el-dropdown-item @click="chase">我的订单</el-dropdown-item>
                  <el-dropdown-item @click="out">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

          </div>
          <div class="icon-dl">
            <a @click="drawer = true">
              <el-icon title="购物车" style="flex: 1">
                <ShoppingTrolley/>
              </el-icon>
            </a>
          </div>


          <div class="icon-ht">
            <a @click="backend">
              <el-icon title="进入后台" style="flex: 1">
                <Monitor/>
              </el-icon>
            </a>
          </div>
        </div>
      </el-menu>
    </el-affix>
    <!--        抽屉式购物车-->
    <el-drawer v-model="drawer" title="购物车" :with-header="true" size="25%" style="background-color: #f6f6f6">
      <template #header="{ titleId }">
        <h3 :id="titleId" :class="title">购物车</h3>
      </template>
      <div class="shopping">
        <div class="shopping-title">
        </div>
        <div class="shopping-panel">
          <div class="shopping-content">
            <div class="sop-list" v-for="(item, index) in data.products" :key="index">
              <div class="sop-chbox">
                <!--                多选框-->
                <el-checkbox @click="mychecked(item)" v-model="item.checked"></el-checkbox>
              </div>
              <div class="img-box">
                <a href="/">
                  <img :src="item.imageUrl" alt="">
                </a>
              </div>
              <div class="sop-details">
                <div class="sop-title">{{ item.flowerName }}</div>
                <div class="sop-price">￥{{ item.price }}</div>
                <div class="sop-quantity">
                  <!--                选择器-->
                  <el-input-number :value="item.quantity" v-model="item.quantity" @change="handleChange(item)" :min="1"
                                   :max="10" label="描述文字" size="small"></el-input-number>
                </div>
              </div>
              <div class="sop-delete">
                <!--                删除按钮-->
                <el-button type="danger" @click="del(item.itemId)" :icon="Delete" circle/>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="sop-sum-fixed">
        <div class="sop-sum">
          <span class="sop-left" style="color: #949494;">已选{{ selectedProductsCount }}款</span>
          <div class="sop-center">
            <span>合计:<span style="color: #f2594b;">￥{{ totalSelectedPrice }}</span></span>
          </div>
          <el-button class="sop-button" type="button" @click="isSettlement">去结算</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import {computed, reactive, ref} from "vue";
import {User, Monitor, ShoppingTrolley, Delete, Search} from "@element-plus/icons-vue";
import {ElAvatar, ElMessage} from "element-plus";
import router from "@/router";
import request from "@/utils/request";

const drawer = ref(false)

const data = reactive({
  user: JSON.parse(localStorage.getItem('xm-pro-user')),
  isLoggedIn: false,
  avatar: 'https://img1.baidu.com/it/u=1667771930,1956496342&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400',
  tableData: [],
  search: '',
  num: 1,
  allPrice: 0,
  products: [],
  myProducts: [],
})


const mychecked = (item) => {
  console.log(item)
  setTimeout(() => {
    request.put("/shoppingcart/quantity", item).then(res => {
      console.log(res)
    })
  }, 500)
}

//结算
const isSettlement = () => {
  if (!localStorage.getItem('xm-pro-user')) {
    ElMessage.success("您还未登录，请先登录账号")
  } else {
    if (data.products.filter(product => product.checked).length === 0) {
      console.log(data.products.filter(product => product.checked).length)
      ElMessage.error("请选择商品")
    } else {
      request.get("/shoppingcart/getChecked", {
        params: {
          userId: data.user.id
        }
      }).then(res => {
        console.log(res)
        data.myProducts = res.data
      })
      router.push('/showcart');
    }
  }
}


const selectedProductsCount = computed(() => {
  return data.products.filter(product => product.checked === true).length;
});


// 计算已选中产品的合计价格
const totalSelectedPrice = computed(() => {
  return data.products
      .filter(product => product.checked === true)
      .reduce((sum, product) => sum + parseFloat(product.price.replace('￥', '')) * product.quantity, 0);
});

//删除购物车商品
const del = (itemId) => {
  console.log(itemId)
  request.delete("/shoppingcart/" + itemId).then(res => {
    if (res.code === '0') {
      request.get("/shoppingcart/getAll", {
        params: {
          userId: data.user.id
        }
      }).then(res => {
        console.log(res)
        data.products = res.data
      })
    } else {
      Element.error(res.msg)
    }
  })
}


// 处理数量变化的方法
const handleChange = (value) => {
  console.log(value)
  request.put("/shoppingcart/quantity", value).then(res => {
    console.log(res)
  })
}

const pace = () => {
  // 路由的push方法到/页面
  router.push('/myspace');
}
const out = () => {
  // 清除了本地存储中的所有数据，用于在用户登出时清除他们的会话数据、偏好设置或其他敏感信息。
  ElMessage.success("你已退出登录")
  setTimeout(() => {
    router.push('/');
    localStorage.removeItem("xm-pro-user");
    window.location.reload();
  }, 500)
}


const backend = () => {
  if (!localStorage.getItem('xm-pro-employee')) {
    router.push('/backend-login');
  } else {
    router.push('/Backend');
  }
}

const buy = () => {
  router.push('/buy');
  setTimeout(() => {
    window.location.reload();
  })
}

const load = () => {
  request.get("/flower/search", {
    params: {
      search: data.search
    }
  }).then(res => {
    localStorage.setItem('search', JSON.stringify(res.data))
    data.tableData = res.data
  })
  router.push('/search');
  setTimeout(() => {
    window.location.reload();
  }, 500)
  localStorage.removeItem("search");
}

// 假设的登录状态变量
console.log(data.state);
if (!localStorage.getItem('xm-pro-user')) {
  // router.push('/');
  data.isLoggedIn = false;
} else if (localStorage.getItem('xm-pro-user')) {
  request.get("/shoppingcart/getAll", {
    params: {
      userId: data.user.id
    }
  }).then(res => {
    console.log(res)
    data.products = res.data
    for (let i = 0; i < data.products.length; i++) {
      data.products[i].checked = (res.data[i].checked === "true")
    }
    console.log(data.products.checked)
  })
  data.isLoggedIn = true;
}
// 个人订单
const chase = () => {
  // 路由的push方法到/页面
  router.push('/mypurchase');
}
// 搜索框
const isSearchIconVisible = ref(true);

// 添加处理搜索图标点击事件的方法
const toggleSearch = () => {
  isSearchIconVisible.value = !isSearchIconVisible.value;
};

// 添加处理回车搜索的方法
const handleSearch = () => {
  load();  // 调用你现有的搜索逻辑方法
};

</script>

<style>
.header_right {
  position: absolute; /* 绝对定位将元素定位到右侧 */
  right: 20px;
  font-size: 30px;
  text-align: center;
  display: flex;
  font-weight: bold;
}

.header_right a {
  color: #0e0c0c;
  transition: color 0.3s ease, font-size 0.3s ease; /* 过渡效果,颜色和文字的过度，ease是时间 */
}

.header_right a:hover {
  color: #507a96;
  font-size: 33px;
}

.icon-dl {
  padding-top: 30px;
  padding-right: 30px;
}

.icon-ht {
  padding-top: 30px;
  padding-right: 20px;
}

.el-menu--horizontal {
  --el-menu-horizontal-height: 80px;
}

.marLefr {
  width: 150px;
}

.marLefr:hover {
  font-size: 16px;
  background: none !important; /* 强制背景色为透明 */
  background-color: transparent;
  color: #bd3725 !important;
  text-decoration: none;
}

.shopping {
  display: flex;
  flex-direction: column;
  width: 100%;
  position: relative; /*能够相对于这个容器进行定位。 */
}

.shopping-content {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 60px;
}

.sop-list {
  display: flex;
  width: 100%;
  position: relative;
  border-bottom: #8d8d8d 1px dashed;
  margin-bottom: 20px;
  padding-bottom: 20px;
}

.sop-chbox {
  margin-top: 20px;
  margin-right: 15px;
}

.img-box {
  flex: 0 0 85px;
  overflow: hidden;
  margin-right: 20px;
}

.img-box img {
  width: 100%;
  height: auto;
  border: 1px solid #d9d9d9;
}

.sop-details {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.sop-title {
  font-size: 16px;
  color: #646464;
}

.sop-price {
  color: #f2594b;
  font-size: 13px;
  margin-top: 5px;
}

.sop-quantity {
  margin-top: 10px;
}

.sop-sum-fixed {
  position: absolute;
  width: 100%;
  bottom: 0;
  right: 2px;
  background-color: #fff;
  border-top: 1px solid #ccc;
  padding: 20px;
  box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
  z-index: 1000; /* 使其位于其他内容之上。 */

}

.sop-sum {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-between;
}

.sop-left {
  margin-right: 80px;
}

.sop-center {
  margin-right: auto;
  text-align: right;
}

.sop-button {
  width: 100px;
  height: 50px;
  background-color: #f2594b;
  color: #FFFFFF;
  border-radius: 4px;
}

.sop-button:hover {
  background-color: #ee2b2b;
  color: #FFFFFF;
}

.sop-delete {
  display: flex;
  margin-top: 30px;
}
</style>